package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
)

type UsersHandler struct {
	*Handler
	usersService service.UsersService
}

func NewUsersHandler(
	handler *Handler,
	usersService service.UsersService,
) *UsersHandler {
	return &UsersHandler{
		Handler:      handler,
		usersService: usersService,
	}
}

func (h *UsersHandler) UsersLogin(ctx *gin.Context) {
	req := new(v1.UsersLoginRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	users, token, err := h.usersService.UsersLogin(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, v1.UsersLoginResponse{
		Token: token,
		Name:  users.Name,
		Id:    users.ID,
	})
}
func (h *UsersHandler) UsersRegister(ctx *gin.Context) {
	var req v1.UsersRegisterRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}

	_, err := h.usersService.UsersRegister(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}

	v1.HandleSuccess(ctx, gin.H{
		"message": "注册成功",
	})
}

func (h *UsersHandler) ChangePassword(ctx *gin.Context) {

	var req v1.UsersChangePasswordRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)

	}

	err := h.usersService.ChangePassword(ctx, req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
	}

	v1.HandleSuccess(ctx, nil)
}
